<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="submitForm('ruleForm')">保存</el-button>
            </div>

            <div class="table-form-box">
                <h3 class="h3">销售合同</h3>
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
                    <table border="0" width="100%" cellpadding="0" cellspacing="1">
                        <tbody>
                            <tr class="tr-title">
                                <td colspan="8">基本信息</td>
                            </tr>
                            <tr>
                                <td align="right">合同编号:</td>
                                <td>
                                    <el-form-item prop="clientContractNo">
                                         <el-input
                                            v-model="ruleForm.clientContractNo"
                                            size="small"
                                            disabled
                                        ></el-input>
                                    </el-form-item>
                                </td>
                                <td align="right"><span class="color-ff2200">*</span>合同名称:</td>
                                <td>
                                    <el-form-item prop="clientContractName">
                                         <el-input
                                            v-model="ruleForm.clientContractName"
                                            size="small"
                                        ></el-input>
                                    </el-form-item>
                                </td>
                               
                            </tr>
                            <tr>
                                <td align="right"><span class="color-ff2200">*</span>签订日期:</td>
                                <td>
                                    <el-form-item prop="signTime">
                                        <el-date-picker
                                            style="width:99%"
                                            v-model="ruleForm.signTime"
                                            align="right"
                                            type="date"
                                            placeholder="选择日期"
                                        ></el-date-picker>
                                    </el-form-item>
                                </td>
                                <td align="right">
                                    <span class="color-ff2200">*</span>关联客户:
                                </td>
                                <td>
                                    <el-form-item prop="linkClientName">
                                        <div @click="showCustomerDialog('客户')">
                                            <el-input
                                                placeholder="请输入"
                                                v-model="ruleForm.linkClientName"
                                                size="small"
                                                readonly
                                            >
                                                <i slot="suffix" class="el-icon-search"></i>
                                            </el-input>
                                        </div>
                                    </el-form-item>
                                </td>
                            </tr>
                            <tr>
                               <td align="right">责任人:</td>
                                <td>
                                    <el-form-item prop="dutyUserName">
                                        <el-input
                                            placeholder="请输入"
                                            v-model="ruleForm.dutyUserName"
                                            size="small"
                                            disabled
                                        />
                                    </el-form-item>
                                </td>
                                <td align="right"><span class="color-ff2200">*</span>合同金额:</td>
                                <td>
                                    <el-form-item prop="clientContractMoney">
                                        <el-input
                                            v-model="ruleForm.clientContractMoney"
                                            size="small"
                                        ></el-input>
                                    </el-form-item>
                                </td>
                               
                            </tr>
                            <tr>
                                <td align="right">备注:</td>
                                <td colspan="5">
                                    <el-form-item prop="remark">
                                        <el-input v-model="ruleForm.remark" type="textarea"></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
         
                        </tbody>
                    </table>
                </el-form>
            </div>
            <!-- 上传附件 -->
            <upload-files :files="fileList" @fun="dealFiles" v-if="flag"></upload-files>
            <div style="margin-top:10px;border:1px solid">
                <div style="margin:10px;">
                    <vxe-toolbar>
                        
                        <template v-slot:buttons>
                            收款计划
                            <vxe-button
                                status="primary"
                                icon="fa fa-plus"
                                @click="insertEvent(-1)"
                            >新增行</vxe-button>
                            <vxe-button status="danger" @click="deleteCheckBoxRow()">删除选中行</vxe-button>
                        </template>
                    </vxe-toolbar>

                    <vxe-table
                        keep-source
                        stripe
                        border
                        show-footer
                        :footer-method="footerMethod"
                        resizable
                        ref="xTable"
                        :data="tableData"
                        :edit-rules="validRules"
                        :edit-config="{trigger: 'click', mode: 'cell'}"
                    >
                        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                        <vxe-table-column type="seq" width="60"></vxe-table-column>
                        <vxe-table-column
                            field="itemName"
                            title="计划日期"
                            :edit-render="{name: 'input', attrs: {type: 'date'}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="points"
                            title="金额"
                            :edit-render="{name: '$input', props: {type: 'number',min:0,max:999999999}}"
                        ></vxe-table-column>
                        <vxe-table-column
                            field="description"
                            title="备注"
                            :edit-render="{name: 'input', attrs: {type: 'text'}}"
                        ></vxe-table-column>
                        
                    </vxe-table>
                </div>
            </div>
        </div>
        <!-- 用户树搜索 -->
        <tree-search
            :isShow="showSearch"
            :dialogTitle="searchDialogTit"
            @edit="searchBack"
            @close="closeDialog"
        ></tree-search>
        <customer-search
            :isShow="showCustomerSearch"
            :dialogTitle="customerSearchDialogTit"
            method="clientInfoFindAllPageByDTO"
            @edit="customerSearchBack"
            @close="closeDialog"
        ></customer-search>
    </div>
</template>

<script>
import appMain from '../../../utils/app_main';
import bus from '../../../components/common/bus'
import XEUtils from 'xe-utils';
var checkMoney = (rule, value, callback) => {
    if(value !== '' && !/^(0|[1-9][0-9]*)$/.test(value)) {
        callback(new Error('请输入正确的金额'));
    } else{
        callback();
    }
}

export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            searchDialogTit: '',
            showSearch: false,
            ruleForm: {
                clientContractMoney: '', // 合同金额 format: int64
                clientContractName: '', // 合同名称	
                clientContractNo: '', // 合同编码	
                createTime: '', // 创建时间	format: date-time
                dutyUserId: '', // 责任人id	
                dutyUserName: '', // 责任人	
                expectedPlan: '', // 预期收款计划列表JSON	
                flowNo: '', // 合同流程编号	
                id: '', // 主键	
                linkClientId: '', // 关联的往来单位客户id	
                linkClientName: '', // 关联的往来单位客户名字	
                remark: '', // 备注	
                signTime: '', // 合同签订时间	
                status: '', // 流程状态	
                statusTypeId: '', // 表单类型ID	
                statusTypeName: '', // 单类型名称	
                total: '', // 合计	
                updateTime: '', // 修改时间	format: date-time
                uploadReturns: '', // 附件上传详情	
                uppercase: '', // 大写
            },
            rules: {
                clientContractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
                linkClientName: [{ required: true, message: '请选择客户', trigger: 'change' }],  
                signTime: [{ required: true, message: '请选择签订日期', trigger: 'change' }],  
                clientContractMoney:  [
                    { required: true, message: '请输入金额', trigger: 'blur'},
                    {  validator: checkMoney, trigger: 'blur'}
                    ],
            },
            fileList: [],
            isUpdate: false, //是否是更新
            flag: false,
            customerSearchDialogTit: '',
            showCustomerSearch: false,
            
            validRules: {
                itemName: [{ required: true, message: '计划日期必须填写' }],
                points: [
                    { required: true, message: '计划金额必须填写' },
                    { pattern: '^(0|[1-9][0-9]*)$', message: '格式不正确' }
                ],
                description: [
                    { min: 2, max: 300, message: '长度在 2 到 300 个字符' }
                ]
            },
            tableData: []
        };
    },
    methods: {
         //初始化table
        resetTableData() {
            const length = this.tableData.length;
            if (length < 10) {
                for (let index = 10; index > length; index--) {
                    let record = {
                        description: '',
                        itemName: '',
                        points: ''
                    };
                    this.tableData.push(record);
                }
            }
            console.log('resetTableData', this.tableData);
        },
        // 选择姓名
        showTreeDialog(tit) {
            this.searchDialogTit = tit;
            this.showSearch = true;
        },
        // 责任人搜索结果返回
        searchBack(data) {
            console.log(data.backData, 'searchTreeBack');
            this.ruleForm.dutyUserName = data.backData.name;
            this.ruleForm.dutyUserId = data.backData.id;
            // this.ruleForm.dutyDepartId = data.backData.organizationId // 部门
            // this.ruleForm.dutyDepartName = data.backData.organizationName
            this.showSearch = false;
        },
        // 选择姓名
        showCustomerDialog(tit) {
            this.customerSearchDialogTit = tit;
            this.showCustomerSearch = true;
        },
        // 客户搜索结果返回
        customerSearchBack(data) {
            console.log(data.backData, 'customerSearchBack');
            this.ruleForm.linkClientName = data.backData.name;
            this.ruleForm.linkClientId = data.backData.id;
            // this.ruleForm.clientTypeld = data.backData.clientTypeId; // 类型
            // this.ruleForm.clientTypeName = data.backData.clientTypeName; 
            // this.ruleForm.clientTypeValue = data.backData.clientTypeValue;
            // this.ruleForm.industryId = data.backData.industryId; // 行业
            // this.ruleForm.industryName = data.backData.industryName; 
            // this.ruleForm.industryValue = data.backData.industryValue;
            // this.ruleForm.phone = data.backData.phone
            // this.ruleForm.telphone = data.backData.telphone
            // this.ruleForm.regionName = data.backData.regionName // 区域
            // this.ruleForm.regionId = data.backData.regionId
            this.ruleForm.dutyUserId = data.backData.repId // 责任人
            this.ruleForm.dutyUserName = data.backData.repName
            
            this.showCustomerSearch = false;
        },
        closeDialog (data) {
            this.showSearch = data.showDialog;
            this.showCustomerSearch = false
        },
        // 根据id查找销售合同
        clientContractInfoFindById(id) {
            appMain
                .clientContractInfoFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.ruleForm = res.data.data;
                        if (res.data.data.expectedPlan) {
                            let arr = JSON.parse(res.data.data.expectedPlan)
                            if (arr.length > 0) {
                                this.tableData.splice(0, arr.length)
                                this.tableData = arr.concat(this.tableData)
                            }
                           
                        }
                    } else {
                        this.$message.error('服务器繁忙，请稍后再试');
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        //根据id查询附件
        uploadFileInfoFindById(id) {
            appMain
                .uploadFileInfoFindById({}, id)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.fileList = res.data.data;
                    } else {
                        this.$message.error(res.data.message);
                    }
                    this.flag = true;
                })
                .catch(err => {
                    console.log(err);
                });
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.ruleForm.uploadReturns = this.fileList;
                    //alert('submit!');
                    if (!this.isUpdate) {
                        //添加文件列表
                        //新增
                        this.clientContractInfoInsert();
                    } else {
                        //添加文件列表
                        //更新
                        this.clientContractInfoUpdateById();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        // 上传文件返回
        dealFiles(data) {
            this.fileList = data.backData;
            this.ruleForm.uploadReturns = this.fileList;
        },
         /**
          * vxe-table  start
          * 
          */
        async insertEvent(row) {
            let record = {
                description: '',
                itemName: '',
                points: ''
            };
            let { row: newRow } = await this.$refs.xTable.insertAt(record, row);
            //await this.$refs.xTable.setActiveCell(newRow, 'sex');
            console.log('insertEvent', this.tableData);
        },
        //删除选中列
        deleteCheckBoxRow() {
            let selectRecords = this.$refs.xTable.getCheckboxRecords();
            if (selectRecords.length < 1) {
                this.$message({
                    message: '请选择一条数据',
                    type: 'info'
                });
            } else {
                this.$refs.xTable.removeCheckboxRow();
                this.tableData = this.$refs.xTable.tableData;
            }
        },
        //新增考核模板
        async clientContractInfoInsert() {
            let updateRecords = this.$refs.xTable.tableData;
            let newArr = [];
            updateRecords.map(item => {
                if (item.description !=='' || item.itemName !== '' || item.points!== '' ){
                    newArr.push(item)
                }
            });
            console.log(updateRecords, newArr)
            if (updateRecords.length > 0) {
                const errMap = await this.$refs.xTable.validate(newArr).catch(errMap => errMap);
                if (errMap) {
                    //this.$XModal.message({ status: 'error', message: '请按要求完成评测！' });
                    this.$message.warning('请按要求填写收款计划！');
                } else {
                    //this.$XModal.message({ status: 'success', message: '校验成功！' });
                    let params = this.ruleForm;
                    params.expectedPlan = JSON.stringify(newArr) ;
                    console.log('updateRecords', newArr);
                    appMain
                        .clientContractInfoInsert(params)
                        .then(res => {
                            if (res.data.code === 20000) {
                                if (this.isEdit) {
                                    this.getData();
                                }
                                bus.$emit('close_current_tags')
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });
                    console.log(this.$router);
                }
            } else {
                //this.$XModal.message({ status: 'warning', message: '未选中数据！' });
                this.$message.info('无更新数据');
            }
        },
        //更新模板
        async clientContractInfoUpdateById() {
           let updateRecords = this.$refs.xTable.tableData;
            let newArr = [];
            updateRecords.map(item => {
                 if (item.description !=='' || item.itemName !== '' || item.points!== '' ){
                    newArr.push(item)
                }
            });
            console.log(updateRecords, newArr)
            if (updateRecords.length > 0) {
                const errMap = await this.$refs.xTable.validate(newArr).catch(errMap => errMap);
                if (errMap) {
                    //this.$XModal.message({ status: 'error', message: '请按要求完成评测！' });
                    this.$message.warning('请按要求填写收款计划！');
                } else {
                    //this.$XModal.message({ status: 'success', message: '校验成功！' });
                    let params = this.ruleForm;
                    params.expectedPlan = JSON.stringify(newArr);
                    console.log('updateRecords', newArr);
                    appMain
                        .clientContractInfoUpdateById(params)
                        .then(res => {
                            if (res.data.code === 20000) {
                                if (this.isEdit) {
                                    this.getData();
                                }
                                bus.$emit('close_current_tags')
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });
                    console.log(this.$router);
                }
            } else {
                //this.$XModal.message({ status: 'warning', message: '未选中数据！' });
                this.$message.info('无更新数据');
            }
        },
        //表脚
        footerMethod({ columns, data }) {
            return [
                columns.map((column, columnIndex) => {
                    if (columnIndex === 0) {
                        return '合计';
                    }
                    if (columnIndex === 2) {
                        //console.log('columns', data);
                        let coin = `${XEUtils.sum(data, 'points')}`;
                        this.ruleForm.total = coin;
                        return coin + ' 元';
                    }
                    return '-';
                })
            ];
        }
        /**
         * vxe-table end
         */ 

    },

    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 160;
        this.pageTitle = this.$router.currentRoute.meta.title;
        // this.dictItemForPerfection();
    },
    created() {
        //如果有id过来就是修改的
        if (this.$route.query.id) {
            let id = this.$route.query.id;
            //是更新操作
            this.isUpdate = true;
            //通过id查询对应离职信息
            this.clientContractInfoFindById(id);
            //通过id查询附件信息
            this.uploadFileInfoFindById(id);
        } else {
            this.resetTableData();
            //新增操作
            this.isUpdate = false;
            this.flag = true;
        }
    }
};
</script>

<style  scoped>
.container {
    padding-bottom: 50px;
}
.handle-box {
    padding: 5px 50px;
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}

.table-form-box table {
    background-color: #666;
}
.table-form-box .h3 {
    font-size: 22px;
    text-align: center;
    font-weight: normal;
    padding: 20px 0;
}
.table-form-box table .tr-title td {
    font-size: 14px;
    line-height: 40px;
}
.table-form-box table td,
.table-form-box table th {
    background-color: #fff;
    padding: 4px;
    min-height: 40px;
    font-size: 12px;
}
.color-ff2200 {
    color: #ff2200;
}
</style>